﻿using System;

namespace _5E.Utils.MathHelper
{
    /// <summary>
    /// 程式说明：概率算法
    /// 建立作者：林逸民
    /// 建立日期：2011-04-24
    /// </summary>
    public class Probability
    {
        #region 变量

        /// <summary>
        /// 随机
        /// </summary>
        private readonly Random m_rd = RandomHelper.Instance;

        /// <summary>
        /// 当前概率
        /// </summary>
        private Int32 m_nowProbability;

        /// <summary>
        /// 最大概率
        /// </summary>
        private Int32 m_maxProbability;

        #endregion

        #region 属性

        public bool IsTrigger
        {
            get
            {
                DealProbability();
                return m_nowProbability <= 0 ? false : Computing();
            }
        }

        #endregion

        #region 构造函数

        public Probability(Int32 nowProbability, Int32 maxProbability)
        {
            m_nowProbability = nowProbability;
            m_maxProbability = maxProbability;
        }

        public Probability(Random ran, Int32 nowProbability, Int32 maxProbability)
            : this(nowProbability, maxProbability)
        {
            m_rd = ran;
        }

        #endregion

        #region 私有

        /// <summary>
        /// 处理概率
        /// </summary>
        void DealProbability()
        {
            while (m_nowProbability % 10 == 0 && m_maxProbability % 10 == 0)
            {
                m_nowProbability = m_nowProbability / 10;
                m_maxProbability = m_maxProbability / 10;
            }
        }

        /// <summary>
        /// 计算
        /// </summary>
        bool Computing()
        {
            bool triggle = false;
            if (0 < m_nowProbability)
            {
                if (m_nowProbability < m_maxProbability)
                {
                    //设置一个总概率 和 随机对比概率
                    Int32 totalRate = 0, compareRate = m_rd.Next(m_maxProbability);
                    //循环总概率次数
                    for (Int32 count = 0; count < m_nowProbability; count++)
                    {
                        //叠加每次的概率
                        totalRate += m_rd.Next(m_maxProbability);
                    }
                    //获取平均概率 以及 概率区间(当前概率 / 3)
                    double nowRate = totalRate / m_nowProbability, Int32ervalRate = m_nowProbability / 2;
                    //平均概率是否大于最小概率值    平均概率是否小于最大概率值
                    bool leftRange = nowRate >= compareRate - Int32ervalRate, righeRange = nowRate <= compareRate + Int32ervalRate;
                    //是否触发概率
                    triggle = leftRange && righeRange;
                }
                else
                {
                    triggle = true;
                }
            }
            else
            {
                triggle = false;
            }
            return triggle;
        }

        #endregion
    }
}
